#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2021/9/29 10:40'
# software: PyCharm

import datetime

from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from apps.web import models


class Tracer:

    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """
        用户已登录，在request中赋值
        :param request:
        :return:
        """
        request.tracer = Tracer()
        # 用户已登录就有会user_id，没有给0
        user_id = request.session.get("user_id", 0)
        # user_object对象有值说明已经登录
        user_object = models.UserInfo.objects.filter(pk=user_id).first()
        request.tracer.user = user_object

        # 白名单:没有登录都可以访问的url
        """
        1、获取当前用户访问的url
        2、检查URL是否在白名单中，如果在则可以继续访问，否则判断是否已经登录
        """
        # 获取当前访问的url，然后判断是否在白名单中
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        # 检查用户是否已登录，如果已登录则继续往后走，未登录则返回到登录页面
        if not request.tracer.user:
            return redirect('login')
        # 登录成功之后，访问后台管理时：获取当前用户所拥有的额度
        # 免费额度在交易记录中存储
        # 获取当前用户ID值最大（最近交易记录）
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by("-id").first()
        # 判断是否已过期
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=user_object, status=2, price_policy__category=1).first()

        # 当前登录用户的额度信息
        request.tracer.price_policy = _object.price_policy

    def process_view(self, request, view, args, kwargs):
        """
        :param request:
        :param view:
        :param args:
        :param kwargs:
        :return:
        """
        # 判断URL是否是以manage开头，如果是则判断项目ID是否是我创建 or 参与
        if not request.path_info.startswith("/manage/"):
            return
        project_id = kwargs.get("project_id")
        # 是否是我创建的
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            # 是我创建的项目的话，我就让他通过
            request.tracer.project = project_object
            return

        # 是否是我参与的项目
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user,
                                                                project_id=project_id).first()
        if project_user_object:
            # 是我参与的项目
            request.tracer.project = project_user_object.project
            return

        return redirect('project_list')
